<template>
  <!-- 搜索 -->
  <ContentWrap>
    <el-form class="-mb-15px" :model="queryParams" ref="queryFormRef">
      <el-row :gutter="20">
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="代理名称" prop="agentName">
            <el-input
              v-model="queryParams.agentName"
              placeholder="请输入代理名称"
              clearable
              @keyup.enter="handleQuery"
            />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="代理等级" prop="agentLevelId">
            <AgentLevelSelect v-model="queryParams.agentLevelId" />
          </el-form-item>
        </el-col>
        <!-- <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="订单状态" prop="status">
            <el-select v-model="queryParams.status" clearable placeholder="全部">
              <el-option
                v-for="dict in statusTabs"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="支付方式" prop="payChannelCode">
            <el-select v-model="queryParams.payChannelCode" clearable placeholder="全部">
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.PAY_CHANNEL_CODE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col> -->
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="销售时间" prop="tradeTime">
            <el-date-picker
              v-model="queryParams.tradeTime"
              :shortcuts="defaultShortcuts"
              :disabled-date="disabledDate"
              :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
              end-placeholder="自定义时间"
              start-placeholder="自定义时间"
              type="daterange"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="创建时间" prop="createTime">
            <el-date-picker
              v-model="queryParams.createTime"
              :shortcuts="defaultShortcuts"
              :disabled-date="disabledDate"
              :default-time="[new Date('1 00:00:00'), new Date('1 23:59:59')]"
              end-placeholder="自定义时间"
              start-placeholder="自定义时间"
              type="daterange"
              value-format="YYYY-MM-DD HH:mm:ss"
            />
          </el-form-item>
        </el-col>
        <el-col :xs="24" :sm="12" :md="8" :lg="6" :xl="4">
          <el-form-item label="结算状态" prop="terminal">
            <el-select v-model="queryParams.terminal" clearable placeholder="全部">
              <el-option
                v-for="dict in getIntDictOptions(DICT_TYPE.TERMINAL)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>

        <el-col :xs="24" :sm="12" :md="6" :lg="6" :xl="4">
          <el-form-item>
            <el-button @click="handleQuery">
              <Icon class="mr-5px" icon="ep:search" />
              搜索
            </el-button>
            <el-button @click="resetQuery">
              <Icon class="mr-5px" icon="ep:refresh" />
              重置
            </el-button>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>
  </ContentWrap>

  <!-- 统计卡片 -->
  <el-row :gutter="10">
    <el-col :xl="6" :lg="6" :md="6" :sm="24" :xs="24" v-loading="loading">
      <SummaryCard
        title="订单数量"
        class="mb-10px"
        icon="icon-park-outline:transaction-order"
        icon-color="bg-blue-100"
        icon-bg-color="text-blue-500"
        :value="summary?.orderCount || 0"
      />
    </el-col>

    <el-col :xl="6" :lg="6" :md="6" :sm="24" :xs="24" v-loading="loading">
      <SummaryCard
        title="订单金额"
        class="mb-10px"
        icon="streamline:money-cash-file-dollar-common-money-currency-cash-file"
        icon-color="bg-purple-100"
        icon-bg-color="text-purple-500"
        prefix="￥"
        :decimals="2"
        :value="Number(fenToYuan(summary?.orderTotalPrice || 0))"
      />
    </el-col>
    <el-col :xl="6" :lg="6" :md="6" :sm="24" :xs="24" v-loading="loading">
      <SummaryCard
        title="订单实售"
        class="mb-10px"
        icon="streamline:money-cash-file-dollar-common-money-currency-cash-file"
        icon-color="bg-purple-100"
        icon-bg-color="text-purple-500"
        prefix="￥"
        :decimals="2"
        :value="Number(fenToYuan(summary?.orderRealPrice || 0))"
      />
    </el-col>
    <el-col :xl="6" :lg="6" :md="6" :sm="24" :xs="24" v-loading="loading">
      <SummaryCard
        title="下单人数"
        class="mb-10px"
        icon="icon-park-outline:transaction-order"
        icon-color="bg-blue-100"
        icon-bg-color="text-blue-500"
        :value="summary?.orderUser || 0"
      />
    </el-col>
    <el-col :xl="6" :lg="6" :md="6" :sm="24" :xs="24" v-loading="loading">
      <SummaryCard
        title="代理数量"
        class="mb-10px"
        icon="icon-park-outline:transaction-order"
        icon-color="bg-blue-100"
        icon-bg-color="text-blue-500"
        :value="summary?.agentNum || 0"
      />
    </el-col>
    <el-col :xl="6" :lg="6" :md="6" :sm="24" :xs="24" v-loading="loading">
      <SummaryCard
        title="累计佣金"
        class="mb-10px"
        icon="streamline:money-cash-file-dollar-common-money-currency-cash-file"
        icon-color="bg-purple-100"
        icon-bg-color="text-purple-500"
        prefix="￥"
        :decimals="2"
        :value="Number(fenToYuan(summary?.rebatePrice || 0))"
      />
    </el-col>
    <el-col :xl="6" :lg="6" :md="6" :sm="24" :xs="24" v-loading="loading">
      <SummaryCard
        title="退款金额"
        class="mb-10px"
        icon="ri:refund-2-line"
        icon-color="bg-green-100"
        icon-bg-color="text-green-500"
        prefix="￥"
        :decimals="2"
        :value="Number(fenToYuan(summary?.afterSalePrice || 0))"
      />
    </el-col>
  </el-row>
  <!-- 列表 -->

  <ContentWrap>
    <el-tabs v-model="queryParams.status" @tab-click="handleQuery">
      <el-tab-pane
        v-for="item in statusTabs"
        :key="item.value"
        :label="item.label"
        :name="item.value"
      >
        <template #label>
          <span>{{ `${item.label} (${summary?.statusMap[`order${item.value}`] || 0})` }}</span>
        </template>
      </el-tab-pane>
    </el-tabs>

    <!-- 添加 row-key="id" 解决列数据中的 table#header 数据不刷新的问题  -->
    <el-table
      v-loading="loading"
      :data="list"
      row-key="id"
      :cell-style="{ padding: 0, borderBottom: 'none' }"
      :header-cell-style="{ padding: 0 }"
      :row-class-name="'table-row-class'"
    >
      <OrderTableColumn :list="list" :pick-up-store-list="pickUpStoreList">
        <template #default="{ row }">
          <div class="flex items-center justify-center">
            <el-button
              v-hasPermi="['trade:order:query']"
              link
              type="primary"
              @click="openDetail(row.id)"
            >
              <Icon icon="ep:notification" />
              详情
            </el-button>
            <el-dropdown
              v-hasPermi="['trade:order:update']"
              @command="(command) => handleCommand(command, row)"
            >
              <el-button link type="primary">
                <Icon icon="ep:d-arrow-right" />
                更多
              </el-button>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="cancel">
                    <Icon icon="ep:chat-line-square" />
                    撤销订单
                  </el-dropdown-item>
                  <!--  <el-dropdown-item command="">
                    <Icon icon="ep:chat-line-square" />
                    打印小票
                  </el-dropdown-item> -->
                  <el-dropdown-item command="">
                    <Icon icon="ep:chat-line-square" />
                    申请退款
                  </el-dropdown-item>
                  <el-dropdown-item
                    command="updatePrice"
                    v-if="row.status! === TradeOrderStatusEnum.UNPAID.status"
                  >
                    <Icon icon="ep:chat-line-square" />
                    订单改价
                  </el-dropdown-item>
                  <el-dropdown-item
                    command="onPay"
                    v-if="row.status! === TradeOrderStatusEnum.UNPAID.status"
                  >
                    <Icon icon="ep:chat-line-square" />
                    继续支付
                  </el-dropdown-item>
                  <!-- <el-dropdown-item command="">
                    <Icon icon="ep:chat-line-square" />
                    线下支付
                  </el-dropdown-item> -->
                  <el-dropdown-item command="logs">
                    <Icon icon="ep:chat-line-square" />
                    订单日志
                  </el-dropdown-item>
                  <!-- 如果是【快递】，并且【未发货】，则展示【发货】按钮 -->
                  <el-dropdown-item
                    v-if="
                      row.deliveryType === DeliveryTypeEnum.EXPRESS.type &&
                      row.status === TradeOrderStatusEnum.UNDELIVERED.status
                    "
                    command="delivery"
                  >
                    <Icon icon="ep:takeaway-box" />
                    订单发货
                  </el-dropdown-item>
                  <el-dropdown-item command="remark">
                    <Icon icon="ep:chat-line-square" />
                    订单备注
                  </el-dropdown-item>
                </el-dropdown-menu>
              </template>
            </el-dropdown>
          </div>
        </template>
      </OrderTableColumn>
      <template #empty>
        <Empty />
      </template>
    </el-table>
    <!-- 分页 -->
    <Pagination
      v-model:limit="queryParams.pageSize"
      v-model:page="queryParams.pageNo"
      :total="total"
      @pagination="getList"
    />
  </ContentWrap>
</template>

<script lang="ts" setup>
import type { FormInstance } from 'element-plus'

import * as TradeOrderApi from '@/api/mall/trade/order'
import AgentLevelSelect from '@/views/mall/trade/agent/level/components/AgentLevelSelect.vue'
import * as PickUpStoreApi from '@/api/mall/trade/delivery/pickUpStore'

import { DICT_TYPE, getIntDictOptions, getStrDictOptions } from '@/utils/dict'
import { DeliveryTypeEnum, TradeOrderStatusEnum } from '@/utils/constants'
import { OrderTableColumn } from './components'
import { appendEmployee, fenToYuan } from '@/utils'
import SummaryCard from '@/components/SummaryCard/index.vue'
import { defaultShortcuts } from '@/utils/formatTime'
/**时间范围限制 */
const disabledDate = (time: Date) => {
  return time.getTime() > Date.now()
}
defineOptions({ name: 'TradeOrder' })
const { currentRoute, push } = useRouter() // 路由跳转
const loading = ref(true) // 列表的加载中
// const exportLoading = ref(false) // 导出的加载中
const total = ref(2) // 列表的总页数
const list = ref<TradeOrderApi.OrderVO[]>([{}]) // 列表的数据
const queryFormRef = ref<FormInstance>() // 搜索的表单
const summary = ref<TradeOrderApi.TradeOrderSummaryRespVO>() // 订单统计数据
const pickUpStoreList = ref<PickUpStoreApi.DeliveryPickUpStoreVO[]>([]) // 自提门店精简列表

// 表单搜索
const queryParams = ref({
  typeClass: 8, //订单分类 8 代理订单
  pageNo: 1, // 页数
  pageSize: 10, // 每页显示数量
  status: '', // 订单状态
  payChannelCode: undefined, // 支付方式
  tradeTime: undefined, //销售时间
  createTime: undefined, // 创建时间
  terminal: undefined, // 订单渠道
  type: undefined, // 订单类型
  agentName: undefined
})

/** 查询列表 */
const getList = async () => {
  loading.value = true
  try {
    // 统计
    summary.value = await TradeOrderApi.getOrderSummary(unref(queryParams))
    const data = await TradeOrderApi.getOrderPage(unref(queryParams))
    list.value = data.list
    // 处理单一销售员工时 列表展示问题,将单一销售员工 合并到 订单列表中
    appendEmployee(list)
    total.value = data.total
  } finally {
    loading.value = false
  }
  loading.value = false
}

/** 搜索按钮操作 */
const handleQuery = async () => {
  nextTick(async () => {
    queryParams.value.pageNo = 1
    await getList()
  })
}

/** 重置按钮操作 */
const resetQuery = () => {
  queryFormRef.value?.resetFields()
  queryParams.value = {
    typeClass: 8, //订单分类 8 代理订单
    pageNo: 1, // 页数
    pageSize: 10, // 每页显示数量
    status: '', // 订单状态
    payChannelCode: undefined, // 支付方式
    tradeTime: undefined, //销售时间
    createTime: undefined, // 创建时间
    terminal: undefined, // 订单渠道
    type: undefined, // 订单类型
    agentName: undefined
  }
  handleQuery()
}
/** 导出按钮操作
const handleExport = async () => {
  try {
    // 导出的二次确认
    await message.exportConfirm()
    // 发起导出
    exportLoading.value = true
    const data = await TradeOrderApi.export(queryParams)
    download.excel(data, '订单列表.xls')
  } catch {
  } finally {
    exportLoading.value = false
  }
}
 */
/** 查看订单详情 */
const openDetail = (id: number) => {
  console.log(id)
  push({ name: 'TradeOrderDetail', params: { id } })
}

/** 操作分发 */

const updateRemarkForm = ref()
const updatePriceFormRef = ref() // 订单调价表单 Ref
const cancelRemarkFormRef = ref()
const handleCommand = (command: string, row: TradeOrderApi.OrderVO) => {
  switch (command) {
    case 'updatePrice':
      updatePriceFormRef.value?.open(row)
      break
    case 'logs':
      openDetail(row.id as number)
      break
    case 'remark':
      updateRemarkForm.value?.open(row)
      break
    case 'cancel':
      cancelRemarkFormRef.value?.open(row)
      break
  }
}

// 监听路由变化更新列表，解决订单保存/更新后，列表不刷新的问题。
watch(
  () => currentRoute.value,
  () => {
    getList()
  }
)

const statusTabs = ref([
  {
    label: '全部',
    value: ''
  }
])
/** 初始化 **/
onMounted(async () => {
  await getList()
  pickUpStoreList.value = await PickUpStoreApi.getListAllSimple()

  // 设置 statuses 过滤
  // for (const dict of getDictOptions(DICT_TYPE.TRADE_ORDER_STATUS)) {
  //   statusTabs.value.push({
  //     label: dict.label,
  //     value: dict.value
  //   })
  // }
})
</script>
<style lang="scss" scoped>
.sort-select {
  :deep(.el-select__wrapper) {
    height: 40px;
  }
}
:deep(.order-table-col > .cell) {
  padding: 0;
}
:deep(.table-row-class) {
  --el-table-row-hover-bg-color: transparent;
}
</style>
